import auth from '@/plugins/auth'
import router, { constantRoutes, dynamicRoutes } from '@/router'
import { GetMenu } from '@/api/apis/menuManage'
import { authApi } from '@/api/apis/auth'
import { getInfo } from '@/utils/auth'
import Layout from '@/layout/index'
import ParentView from '@/components/ParentView'
import InnerLink from '@/layout/components/InnerLink'

const permission = {
  state: {
    routes: [],
    addRoutes: [],
    defaultRoutes: [],
    topbarRouters: [],
    sidebarRouters: []
  },
  mutations: {
    SET_ROUTES: (state, routes) => {
      routes.forEach(item => {
        if (item.path === '/applicationList') {
          item.children.forEach(ele => {
            if (ele.path === 'settingMenu') {
              ele.redirect = 'settingMenu/applicationEdit'
              ele.children = [
                {
                  path: 'applicationEdit',
                  component: () => import('@/views/applicationList/applicationAdd.vue'),
                  name: 'applicationEdit',
                  hidden: true,
                  meta: {
                    title: '应用编辑',
                    hidden: true
                  }
                },
                {
                  path: 'exploit',
                  component: () => import('@/views/applicationList/exploit'),
                  name: 'exploit',
                  hidden: true,
                  meta: {
                    title: '开发管理',
                    hidden: true
                  }
                },
                {
                  path: 'authority',
                  component: () => import('@/views/applicationList/authority'),
                  name: 'authority',
                  hidden: true,
                  meta: {
                    title: '权限管理',
                    hidden: true

                  }
                },
                {
                  path: 'appApiAdmin',
                  name: 'appApiAdmin',
                  component: () => import('@/views/applicationList/apiList/apiAdmin'),
                  meta: {
                    title: 'API管理',
                    hidden: true
                  }
                },
                {
                  path: 'inserterAdmin',
                  name: 'inserterAdmin',
                  component: () => import('@/views/applicationList/inserterAdmin'),
                  meta: {
                    title: '插件管理',
                    hidden: true
                  }
                },
                {
                  path: 'appApiadd',
                  name: 'appApiAdd',
                  redirect: '',
                  hidden: 'true',
                  component: () => import('@/views/applicationList/apiList/apiAdd'),
                  meta: {
                    title: 'API新增'

                  }
                },
                {
                  path: 'appApiview',
                  name: 'appApiView',
                  hidden: 'true',
                  component: () => import('@/views/applicationList/apiList/apiView'),
                  meta: {
                    title: 'API查看'
                  }
                }
              ]
            }
          })
        } else if (item.path === '/integrationOption') {
          item.children.forEach(ele => {
            if (ele.path === 'settingMenu') {
              ele.redirect = 'settingMenu/masterDataEdit'
              ele.children = [
                {
                  path: 'masterDataEdit',
                  component: () => import('@/views/masterDataOptions/masterDataAdd.vue'),
                  name: 'masterDataEdit',
                  hidden: true,
                  meta: {
                    title: '基本信息',
                    hidden: true
                  }
                },
                {
                  path: 'dataOrigin',
                  component: () => import('@/views/masterDataOptions/dataOrigin'),
                  name: 'dataOrigin',
                  hidden: true,
                  meta: {
                    title: '数据源',
                    hidden: true
                  }
                },
                {
                  path: 'displayInfo',
                  component: () => import('@/views/masterDataOptions/displayInfo'),
                  name: 'displayInfo',
                  hidden: true,
                  meta: {
                    title: '显示信息',
                    hidden: true

                  }
                },
                {
                  path: 'authorily',
                  name: 'authorily',
                  component: () => import('@/views/masterDataOptions/authority'),
                  meta: {
                    title: '配置权限',
                    hidden: true
                  }
                },
                {
                  path: 'distribute',
                  name: 'distribute',
                  component: () => import('@/views/masterDataOptions/distribute'),
                  meta: {
                    title: '分发设置',
                    hidden: true
                  }
                }
              ]
            }
          })
        }
      })
      state.addRoutes = routes
      state.routes = constantRoutes.concat(routes)
      // state.routes = routes
    },
    SET_DEFAULT_ROUTES: (state, routes) => {
      state.defaultRoutes = constantRoutes.concat(routes)
    },
    SET_TOPBAR_ROUTES: (state, routes) => {
      state.topbarRouters = routes
    },
    SET_SIDEBAR_ROUTERS: (state, routes) => {
      state.sidebarRouters = routes
    },
    REMOVE_ROUTER: (state, routes) => {
      state.routes = []
      state.addRoutes = []
    }
  },
  actions: {
    // 生成路由
    GenerateRoutes({ commit }) {
      return new Promise((resolve) => {
        let params = {
          id: JSON.parse(getInfo()).id
        }
        authApi('sysMenuConfigService', '', 'queryTreeById', '', params).then((res) => {
          const sdata = JSON.parse(JSON.stringify(res.attribute))
          const rdata = JSON.parse(JSON.stringify(res.attribute))
          const sidebarRoutes = filterAsyncRouter(sdata)
          const rewriteRoutes = filterAsyncRouter(rdata, false, true)
          const asyncRoutes = filterDynamicRoutes(dynamicRoutes)
          rewriteRoutes.push({
            path: '*',
            redirect: '/notFound',
            hidden: true
          })
          router.addRoutes(asyncRoutes)
          router.addRoutes(rewriteRoutes)
          console.log(rewriteRoutes,'rewriteRoutes')
          commit('SET_ROUTES', rewriteRoutes)
          // commit("SET_SIDEBAR_ROUTERS", sidebarRoutes);
          commit('SET_DEFAULT_ROUTES', sidebarRoutes)
          commit('SET_TOPBAR_ROUTES', sidebarRoutes)
          commit('SET_SIDEBAR_ROUTERS', constantRoutes.concat(sidebarRoutes))
          resolve(rewriteRoutes)
        })
      })
    }
  }
}

// 遍历后台传来的路由字符串，转换为组件对象
function filterAsyncRouter(asyncRouterMap, lastRouter = false, type = false) {
  return asyncRouterMap.filter((route) => {
    if (type && route.children) {
      route.children = filterChildren(route.children)
    }
    if (route.component) {
      // Layout ParentView 组件特殊处理
      if (route.component === 'Layout') {
        route.component = Layout
      } else if (route.component === 'ParentView') {
        route.component = ParentView
      } else if (route.component === 'InnerLink') {
        route.component = InnerLink
      } else {
        route.component = loadView(route.component)
      }
    }
    if (route.children != null && route.children && route.children.length) {
      route.children = filterAsyncRouter(route.children, route, type)
    } else {
      delete route['children']
      delete route['redirect']
    }
    return true
  })
}

function filterChildren(childrenMap, lastRouter = false) {
  var children = []
  childrenMap.forEach((el, index) => {
    if (el.children && el.children.length) {
      if (el.component === 'ParentView' && !lastRouter) {
        el.children.forEach((c) => {
          c.path = el.path + '/' + c.path
          if (c.children && c.children.length) {
            children = children.concat(filterChildren(c.children, c))
            return
          }
          children.push(c)
        })
        return
      }
    }
    if (lastRouter) {
      el.path = lastRouter.path + '/' + el.path
    }
    children = children.concat(el)
  })
  return children
}

// 动态路由遍历，验证是否具备权限
export function filterDynamicRoutes(routes) {
  const res = []
  routes.forEach((route) => {
    // if (route.permissions) {
    // 	if (auth.hasPermiOr(route.permissions)) {
    // 		res.push(route)
    // 	}
    // } else if (route.roles) {
    // 	if (auth.hasRoleOr(route.roles)) {
    // 		res.push(route)
    // 	}
    // }
    res.push(route)
  })
  return res
}

export const loadView = (view) => {
  // if (process.env.NODE_ENV === 'development') {
  // 	return (resolve) => require([`@/views/${view}`], resolve)
  // } else {
  // 	// 使用 import 实现生产环境的路由懒加载
  // 	// return () => import(`@/views/${view}`)
  // 	// return (resolve) => require([`@/views/${view}`], resolve)
  // 	return () => import(`@/views/${view}`)
  // }
  return (resolve) => require([`@/views/${view}`], resolve)
}

export default permission
